import 'package:dio/dio.dart';

class Request {
  /// get post请求 文件上传
  void ajax({
    required String url,
    required String method,
    dynamic data,
    Map<String, String>? headers,
    required Function(dynamic response) success,
    required Function(dynamic msg) err,
    bool isUploadFile = false, // 新增参数，标识是否为文件上传
  }) async {
    headers ??= {
      "user-agent":
          "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 UOS Community"
    };

    // 创建 BaseOptions 实例并设置头信息
    BaseOptions options = BaseOptions(
      headers: headers,
    );
    // 创建 Dio 实例并设置选项
    Dio dio = Dio(options);
    dio.options.validateStatus = (status) {
      // 这里返回true表示接受所有状态码，不会抛出异常
      return true;
    };

    try {
      Response response;
      if (method == 'GET') {
        response = await dio.get(url);
      } else if (method == 'POST') {
        if (isUploadFile) {
          // 如果是文件上传，设置 Content-Type 为 multipart/form-data
          Map<String, dynamic> files = {};
          for (var key in data.keys) {
            files[key] = await MultipartFile.fromFile(data[key] as String);
          }
          FormData formData = FormData.fromMap(files);
          response = await dio.post(url, data: formData);
        } else {
          // 如果不是文件上传，设置 Content-Type 为 application/x-www-form-urlencoded
          dio.options.headers['Content-Type'] =
              'application/x-www-form-urlencoded';
          response = await dio.post(url, data: data);
        }
      } else {
        err({
          'status': 0,
          'msg': 'Unsupported method',
        });
        return;
      }

      if (response.statusCode == 200) {
        success(response.data);
      } else if (response.statusCode == 302) {
        err({
          'status': response.statusCode,
          'url': response.headers.value('location')
        });
      } else {
        err({'status': response.statusCode, 'response': response});
      }
    } on DioException catch (e) {
      err({
        'status': -1,
        'msg': e,
      });
    }
  }

  void download({
    required String url,
    required String savePath,
    Map<String, String>? headers,
    required Function(dynamic response) success,
    required Function(dynamic msg) err,
    Function(int receivedBytes, int totalBytes)? onReceiveProgress,
  }) async {
    headers ??= {
      "user-agent":
          "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 UOS Community"
    };
    onReceiveProgress ??= (receivedBytes, totalBytes) {};
    Dio dio = Dio();
    dio.options.validateStatus = (status) {
      // 这里返回true表示接受所有状态码，不会抛出异常
      return true;
    };
    try {
      Response response = await dio.download(url, savePath,
          options: Options(headers: headers),
          onReceiveProgress: onReceiveProgress);
      // 当下载成功时，调用 success 回调函数
      if (response.statusCode == 200) {
        success(savePath);
      } else if (response.statusCode == 302) {
        err({
          'status': response.statusCode,
          'url': response.headers.value('location')
        });
      } else {
        err({'status': response.statusCode, 'response': response});
      }
    } catch (e) {
      //error, stackTrace
      // 当下载失败时，调用 err 回调函数，并传入错误信息
      err({
        'status': -1,
        'msg': e,
      });
    }
  }
}
